<template>
	<view class="p-4 text-base">
		<view class="text-h4 mb-2">选号参数</view>
		<view class="text-base mb-4">推荐方案：【初选/7列选号池/过滤2】、【初选/前后区选号池/过滤3】、【优选/7列选号池/过滤2】、【优选/前后区选号池/过滤3】中奖率最佳。</view>
		<uni-forms :modelValue="paramFormData">
			<uni-forms-item label="选号模式">
				<uni-data-select v-model="paramFormData.chooseMode"
					:localdata="ssqTplModel.ChooseModeData"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="号源类型">
				<uni-data-select v-model="paramFormData.poolType"
					:localdata="ssqTplModel.PoolTypeData"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="号池过滤">
				<uni-data-select v-model="paramFormData.filterLevel"
					:localdata="ssqTplModel.FilterLevelData"></uni-data-select>
			</uni-forms-item>
		</uni-forms>
		<view class="text-h4 my-2">复盘开奖</view>
		<view class="flex items-center justify-between">
			<view class="me-1">本期：{{activeDrawInfo.lotteryDrawNum}}</view>
			<uni-easyinput v-model="activeDrawInfo.lotteryDrawResult" placeholder="本期开奖号码" />
		</view>
		<view class="flex items-center my-1">
			<view class="me-4">上期：{{prevDrawInfo.lotteryDrawNum}}</view>
			<view>{{prevDrawInfo.lotteryDrawResult}}</view>
		</view>
		<view class="flex items-center justify-between mb-2">
			<view>复盘：</view>
			<uni-data-select :localdata="historyData" @change="onChangeHistoryData"></uni-data-select>
		</view>
		<view class="text-h4 my-2">数量设置</view>
		<view class="flex items-center justify-between">
			<view class="flex items-center justify-between me-2">
				<view class="me-1">每批：</view>
				<uni-easyinput v-model="batchFormData.listCount" type="number" />
				<view>注</view>
			</view>
			<view class="flex items-center justify-between">
				<view class="me-1">共：</view>
				<uni-easyinput v-model="batchFormData.batchCount" type="number" />
				<view>批</view>
			</view>
		</view>
		<view class="my-2">
			<button size="mini" type="primary" @click="batchGenerateOrders()">生成号码</button>
			<button size="mini" class="mx-1" @click="onReset()">重置</button>
		</view>
		<view class="text-h4 my-2">统计汇总</view>
		<view class="lh-lg">
			<view>总共：{{statInfo.totalBatchCount}}批 / {{statInfo.totalTicketCount}}注（100%）</view>
			<view>盈利批次量：{{statInfo.profitBatchCount}}批（{{statInfo.profitBatchCountRate}}%） /
				亏损批次量：{{statInfo.lossBatchCount}}批（{{statInfo.lossBatchCountRate}}%)</view>
			<view>有中奖批次量：{{statInfo.winBatchCount}}批（{{statInfo.winBatchCountRate}}%） /
				没中奖批次量：{{statInfo.noWinBatchCount}}批（{{statInfo.noWinBatchCountRate}}%）</view>
			<view>总收入：{{statInfo.totalIncome}}元 / 总支出：{{statInfo.totalExpenses}}元 / 净利润：{{statInfo.netProfitMoney}}元
			</view>
			<view v-for="i in 2" :key="i">
				{{statInfo['win'+i].title}}：{{statInfo['win'+i].totalTicketCount}}注（{{`${statInfo['win'+i].prizeMoney}万*${statInfo['win'+i].totalTicketCount}=${statInfo['win'+i].totalIncome}万元`}}）
			</view>
			<template v-for="i in 9">
				<view v-if="i>2" :key="i" :class="statInfo['win'+i].totalIncome>0 ? 'text-red-400' : ''">
					{{statInfo['win'+i].title}}：{{statInfo['win'+i].totalTicketCount}}注（{{`${statInfo['win'+i].prizeMoney}*${statInfo['win'+i].totalTicketCount}=${statInfo['win'+i].totalIncome}元`}}）
				</view>
			</template>
		</view>
		<view class="text-h4 my-2">详情（按奖项高低排序）</view>
		<view v-for="i in 9" :key="i">
			<view :class="'text-h5 my-2 ' + (statInfo['win'+i].totalIncome>0 ? 'text-red-400' : '')">
				{{statInfo['win'+i].title}}（{{statInfo['win'+i].totalBatchCount}}批，{{statInfo['win'+i].totalTicketCount}}注）
			</view>
			<view v-for="(item2, idx2) in statInfo['win'+i].list" :key="idx2">
				<view>
					第 {{item2.id}} 批（{{(item2.netProfitMoney > 0 ? '盈利' : '亏损') + Math.abs(item2.netProfitMoney) + '元'}}）
				</view>
				<view class="flex items-center lh-lg" v-for="(item3, idx3) in item2.list" :key="idx3">
					<view v-html="item3.text"></view>
					<view class="text-error mx-6">{{`${item3.frontCount}+${item3.backCount}`}}</view>
					<view class="text-error">{{`${item3.statusText}(${item3.moneyText})`}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	import {
		prize_info
	} from '@/config/ssq-config';
	import SsqDataModel from '@/model/SsqDataModel';
	import SsqOrderModel from '@/model/SsqOrderModel';
	import SsqTplModel from '@/model/SsqTplModel';

	const ssqTplModel = new SsqTplModel();
	const ssqDataModel = new SsqDataModel();
	const ssqOrderModel = new SsqOrderModel();
	const dataset = [...ssqDataModel.getDataSource()];
	const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
	const historyData = dataset.map((v, i) => {
		return {
			text: `${v.lotteryDrawNum} （${v.lotteryDrawTime.substring(5)} 周${weekdays[new Date(v.lotteryDrawTime).getDay()]}）（${v.lotteryDrawResult}）`,
			value: i
		};
	});
	const prevDrawInfo = ref(dataset.length > 0 ? dataset[0] : {
		lotteryDrawNum: '',
		lotteryDrawResult: ''
	});
	const activeDrawInfo = ref({
		lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1,
		lotteryDrawResult: ''
	});

	// const tplData = ref({
	// 	...ssqTplModel.getTplForFileData({
	// 		PrevDrawalInfo: prevDrawInfo.value,
	// 		DrawalInfo: {
	// 			lotteryDrawNum: activeDrawInfo.value.lotteryDrawNum,
	// 			lotteryDrawResult: "",
	// 			lotteryDrawTime: ""
	// 		},
	// 	})
	// });

	const resetParamFormData = {
		remark: '',
		chooseMode: '初选',
		poolType: 'columns',
		filterLevel: "1",
	};
	const paramFormData = ref({
		...resetParamFormData
	});

	const resetBatchFormData = {
		listCount: 10,
		batchCount: 10,
	}
	const batchFormData = ref({
		...resetBatchFormData
	});
	const batchList = ref([]);
	const statInfo = ref({
		totalBatchCount: 0, // 总批次数量
		totalTicketCount: 0, // 总注数
		profitBatchCount: 0, // 盈利批次量
		lossBatchCount: 0, // 亏损批次量
		profitBatchCountRate: 0, // 盈利批次量比例
		lossBatchCountRate: 0, // 亏损批次量比例
		winBatchCount: 0, // 有中奖批次量
		noWinBatchCount: 0, // 没中奖批次量
		winBatchCountRate: 0, // 有中奖批次量比例
		noWinBatchCountRate: 0, // 没中奖批次量比例
		totalIncome: 0, // 总收入金额
		totalExpenses: 0, // 总支出金额
		netProfitMoney: 0, // 净收入金额
		// 各奖项详情
		win1: {
			title: '一等奖',
			prizeMoney: 0, // 奖项奖金
			totalBatchCount: 0, // 总批数
			totalTicketCount: 0, // 总注数
			totalIncome: 0, // 总收入金额
			list: [], // 明细
		},
		win2: {
			title: '二等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win3: {
			title: '三等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win4: {
			title: '四等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win5: {
			title: '五等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win6: {
			title: '六等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win7: {
			title: '七等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win8: {
			title: '八等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		},
		win9: {
			title: '九等奖',
			prizeMoney: 0,
			totalBatchCount: 0,
			totalTicketCount: 0,
			totalIncome: 0,
			list: [],
		}
	});
	prize_info.forEach(item => {
		if (item.value == 0) {
			return;
		}
		statInfo.value['win' + item.value].prizeMoney = item.money;
	})
	const onReset = function() {
		paramFormData.value = {
			...resetParamFormData
		};
		batchFormData.value = {
			...resetBatchFormData
		};
		prevDrawInfo.value = dataset.length > 0 ? dataset[0] : {
			lotteryDrawNum: '',
			lotteryDrawResult: ''
		};
		activeDrawInfo.value = {
			lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1,
			lotteryDrawResult: ''
		}
	}
	const onChangeHistoryData = function(value) {
		activeDrawInfo.value = dataset[value];
		prevDrawInfo.value = dataset[value + 1];
	}

	const batchGenerateOrders = () => {
		batchList.value = [];
		for (let i = 0; i < batchFormData.value.batchCount; i++) {
			batchList.value.push({
				...ssqTplModel.getTplForOrderListItem({
					param: paramFormData.value
				})
			})
		}
		let drawResult = activeDrawInfo.value?.lotteryDrawResult?.trim();
		let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim();
		if (!drawResult?.length) {
			uni.showToast({
				title: '请选择复盘的开奖号码',
				icon: 'error'
			})
			return;
		}
		let winBatchList = [];
		for (let i = 0; i < batchFormData.value.batchCount; i++) {
			batchList.value[i].list = [];
			batchList.value[i].drawList = [];
			onChooseAuto(i, 10);
			if (batchList.value[i].param.chooseMode == '优选') {
				batchList.value[i].list = ssqOrderModel.getBetterNums7(batchList.value[i].list)
			}
			// 开奖
			batchList.value[i].drawList = ssqOrderModel.calcOrder(drawResult,
				batchList.value[i].list, true, prevDrawResult);
			// 中奖数据
			if (batchList.value[i].drawList.length > 0) {
				winBatchList.push({
					id: i + 1,
					list: batchList.value[i].drawList,
					maxPrize: ssqOrderModel.getMaxPrize(batchList.value[i].drawList),
					totalIncome: batchList.value[i].drawList.map(v => v.money).reduce((a, b) => {
						return parseInt(a) + parseInt(b)
					}),
				});
			}

		}
		// 中奖汇总统计
		let batchCost = batchFormData.value.listCount * 2; // 每批次开支
		statInfo.value.totalBatchCount = batchFormData.value.batchCount; // 总批次数量
		statInfo.value.totalTicketCount = batchFormData.value.batchCount * batchFormData.value.listCount; // 总注数
		statInfo.value.totalExpenses = statInfo.value.totalTicketCount * 2; // 总支出金额
		statInfo.value.winBatchCount = winBatchList.length; // 有中奖批次量
		statInfo.value.noWinBatchCount = statInfo.value.totalBatchCount - winBatchList.length; // 没中奖批次量
		statInfo.value.winBatchCountRate = Math.round(100 * winBatchList.length / statInfo.value
			.totalBatchCount); // 有中奖批次量比例
		statInfo.value.noWinBatchCountRate = 100 - statInfo.value.winBatchCountRate; // 没中奖批次量比例
		let k = '';
		winBatchList.forEach(item => {
			item.netProfitMoney = item.totalIncome - batchCost;
			if (item.netProfitMoney > 0) {
				statInfo.value.profitBatchCount++; // 盈利批次量
			}
			statInfo.value.totalIncome += item.totalIncome; // 总收入金额
			k = 'win' + item.maxPrize.value;
			statInfo.value[k].list.push(item);
			statInfo.value[k].totalBatchCount++;
			statInfo.value[k].totalTicketCount += item.list.filter(v => v.status == item.maxPrize.value)
				.length;
			statInfo.value[k].totalIncome += item.totalIncome;
		})
		winBatchList = null;
		statInfo.value.lossBatchCount = statInfo.value.totalBatchCount - statInfo.value.profitBatchCount; // 亏损批次量
		statInfo.value.profitBatchCountRate = Math.round(100 * statInfo.value.profitBatchCount / statInfo.value
			.totalBatchCount); // 盈利批次量比例
		statInfo.value.lossBatchCountRate = 100 - statInfo.value.profitBatchCountRate; // 亏损批次量比例
		statInfo.value.netProfitMoney = statInfo.value.totalIncome - statInfo.value.totalExpenses; // 净收入金额
	}

	/**
	 * 机选一注
	 */
	const onChooseAuto = (batchIdx, count = 1) => {
		let nums = [],
			n = count == 1 ? count : (count - batchList.value[batchIdx].list.length);
		let filterLevel = parseInt(batchList.value[batchIdx].param.filterLevel);
		let poolType = batchList.value[batchIdx].param.poolType;
		while (n > 0) {
			nums = ssqOrderModel.getRandomNums7(poolType, filterLevel, prevDrawInfo.value.lotteryDrawResult);
			batchList.value[batchIdx].list.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
			n--;
		}
	}

	/**
	 * 优选（在机选号码里面继续机选）
	 */
	const onChooseAutoBetter = (batchIdx) => {
		if (batchList.value[batchIdx].list.length == 0) {
			uni.showToast({
				title: '请先选择机选的号码',
				icon: 'error'
			})
			return;
		}
		batchList.value[batchIdx].list = ssqOrderModel.getBetterNums7(batchList.value[batchIdx].list);
	}
</script>

<style>
	:deep(.uni-forms-item) {
		margin-bottom: 4px;
	}
</style>